package org.dromara.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.BusinessCollect;
import org.dromara.business.domain.BusinessInformation;
import org.dromara.business.domain.User;
import org.dromara.business.domain.bo.BusinessInformationBo;
import org.dromara.business.domain.vo.BusinessInformationVo;
import org.dromara.business.mapper.BusinessInformationMapper;
import org.dromara.business.service.BusinessCollectService;
import org.dromara.business.service.BusinessInformationService;
import org.dromara.business.service.UserService;
import org.dromara.common.core.domain.R;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 信息
 *
 * @author zlj
 * @date 2024-11-18
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/information")
public class BusinessInformationController extends BaseController {

    private final BusinessInformationService businessInformationService;
    private final BusinessInformationMapper businessInformationMapper;
    private final UserService userService;
    private final BusinessCollectService businessCollectService;

    /**
     * 查询信息列表
     */
    //@SaCheckPermission("system:information:list")
    @GetMapping("/list")
    public TableDataInfo<BusinessInformationVo> list(BusinessInformationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BusinessInformation> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(BusinessInformation::getShzt, "2");
        lambdaQueryWrapper.like(StrUtil.isNotBlank(bo.getBt()), BusinessInformation::getBt, bo.getBt());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(bo.getProvince()), BusinessInformation::getProvince, bo.getProvince());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(bo.getCity()), BusinessInformation::getCity, bo.getCity());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(bo.getDistricts()), BusinessInformation::getDistricts, bo.getDistricts());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(bo.getLxNameYj()), BusinessInformation::getLxNameYj, bo.getLxNameYj());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(bo.getLxNameEj()), BusinessInformation::getLxNameEj, bo.getLxNameEj());

//        lambdaQueryWrapper.orderByDesc(BusinessInformation::getCreateTime);
        lambdaQueryWrapper.orderByDesc(BusinessInformation::getUpdateTime);
        IPage<BusinessInformationVo> voIPage = businessInformationMapper.selectVoPage(pageQuery.build(), lambdaQueryWrapper);
        // IDS
        if (CollectionUtil.isEmpty(voIPage.getRecords())) {
            return TableDataInfo.build(voIPage);
        }
        List<Long> ids = voIPage.getRecords().stream().map(BusinessInformationVo::getId).toList();

        if ("xcx_user".equals(LoginHelper.getUserType().getUserType())) {
            List<BusinessCollect> list = businessCollectService.list(new LambdaQueryWrapper<BusinessCollect>()
                .eq(BusinessCollect::getUserId, LoginHelper.getUserId())
                .in(BusinessCollect::getUserIdPassivity, ids));
            for (BusinessInformationVo vo : voIPage.getRecords()) {

                String title = vo.getBt();
                if (title != null && title.length() > 10) {
                    title = title.substring(0, 10) + "...";
                }
                vo.setBt(title);
                for (BusinessCollect cList : list) {
                    if (vo.getId().equals(cList.getUserIdPassivity())) {
                        vo.setSfxh(true);
                    }
                }
            }
        }
        return TableDataInfo.build(voIPage);
    }

    /**
     * 查询信息列表
     */
    //@SaCheckPermission("system:information:list")
    @GetMapping("/listHt")
    public TableDataInfo<BusinessInformationVo> listHt(BusinessInformationBo bo, PageQuery pageQuery) {
        return businessInformationService.queryPageList(bo, pageQuery);
    }

    /**
     * 我的发布列表
     */
    //@SaCheckPermission("system:information:list")
    @GetMapping("/list2")
    public TableDataInfo<BusinessInformationVo> list2(BusinessInformationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BusinessInformation> lambdaQueryWrapper = new LambdaQueryWrapper<BusinessInformation>();
        lambdaQueryWrapper.eq(BusinessInformation::getCreateBy, LoginHelper.getUserId());
        lambdaQueryWrapper.eq(BusinessInformation::getShzt, bo.getShzt());
        lambdaQueryWrapper.orderByDesc(BusinessInformation::getUpdateTime);
        IPage<BusinessInformation> page = pageQuery.build();
        IPage<BusinessInformationVo> voIPage = businessInformationMapper.selectVoPage(page, lambdaQueryWrapper);
        return TableDataInfo.build(voIPage);
    }

    /**
     * 审核列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/pendingApprovalList")
    public TableDataInfo<BusinessInformationVo> pendingApprovalList(BusinessInformationBo bo, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        User user = userService.getById(userId);
        LambdaQueryWrapper<BusinessInformation> lambdaQueryWrapper = new LambdaQueryWrapper<BusinessInformation>();
        lambdaQueryWrapper.eq(BusinessInformation::getShzt, bo.getShzt());
        lambdaQueryWrapper.eq(BusinessInformation::getCity, user.getProxyRegion());
        lambdaQueryWrapper.orderByDesc(BusinessInformation::getUpdateTime);
        IPage<BusinessInformation> page = pageQuery.build();
        IPage<BusinessInformationVo> voIPage = businessInformationMapper.selectVoPage(page, lambdaQueryWrapper);
        return TableDataInfo.build(voIPage);
    }

    @Log(title = "信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/updateShzt")
    public R<Void> upbateShzt(@RequestBody BusinessInformationBo bo) {
        return toAjax(businessInformationService.updateByBo(bo));
    }

    /**
     * 导出信息列表
     */
    //@SaCheckPermission("system:information:export")
    @Log(title = "信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BusinessInformationBo bo, HttpServletResponse response) {
        List<BusinessInformationVo> list;
        list = businessInformationService.queryList(bo);
        ExcelUtil.exportExcel(list, "信息", BusinessInformationVo.class, response);
    }

    /**
     * 置顶信息的排序
     */
    //@SaCheckPermission("system:information:export")
    @Log(title = "信息", businessType = BusinessType.EXPORT)
    @PostMapping("/refresh")
    public R<Void> refresh(Long id,String type) {
        Boolean b = businessInformationService.refresh(id,type);
        return R.ok(b ? "置顶成功" : "置顶失败");
    }

    /**
     * 获取信息详细信息
     *
     * @param id 主键
     */
    //@SaCheckPermission("system:information:query")
    @GetMapping("/getInfoById")
    public R<Map<String, Object>> getInfo(Long id) {
        BusinessInformationVo vo = BeanUtil.toBean(businessInformationService.getById(id), BusinessInformationVo.class);
        // 查询发布人信息
        User user = userService.getById(vo.getUserId());
        Map<String, Object> map = new HashMap<>();
        // 判断是否收藏
        vo.setSfxh(sfSc(LoginHelper.getUserId(), vo.getId()));
        map.put("vo", vo);
        map.put("user", user);
        return R.ok(map);
    }


    /**
     * 获取信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("business:information:query")
    @GetMapping("/info/{id}")
    public R<BusinessInformationVo> getInfo2(@NotNull(message = "主键不能为空")
                                             @PathVariable Long id) {
        return R.ok(businessInformationService.queryById(id));
    }

    /**
     * 新增信息
     */
    //@SaCheckPermission("system:information:add")
    @Log(title = "信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Transactional
    public R<Void> add(@RequestBody BusinessInformationBo bo) {
        Long userId = LoginHelper.getUserId();
        User user = userService.getById(userId);
        if (bo.getPhoto().contains("undefined")) {
            return R.fail("发布失败,图片上传错误");
        }
//        if ("0".equals(user.getType()) || ObjectUtil.isEmpty(user.getType())) {
//            return R.fail("沒有实名认证");
//        }
//        if (!"3".equals(user.getIfCardReview())) {
//            return R.fail("实名认证没有审批通过");
//        }
        if (user.getHyNumber() > 0) {
            user.setHyNumber(user.getHyNumber() - 1);
            userService.updateById(user);
        } else {
            return R.fail("发布次数已用完");
        }

        bo.setUserId(user.getUserId());
        bo.setVip(user.getVip());
        return toAjax(businessInformationService.insertByBo(bo));
    }

    /**
     * 修改信息
     */
    //@SaCheckPermission("system:information:edit")
    @Log(title = "信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@RequestBody BusinessInformationBo bo) {
        return toAjax(businessInformationService.updateByBo(bo));
    }

    /**
     * 审核发布信息
     *
     * @param bo
     * @return
     */
    @Log(title = "信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/reviewAdvertisements")
    public R<Void> reviewAdvertisements(@RequestBody BusinessInformationBo bo) {
        return toAjax(businessInformationService.reviewAdvertisements(bo));
    }

    /**
     * 删除信息
     *
     * @param ids 主键串
     */
    //@SaCheckPermission("system:information:remove")
    @Log(title = "信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(businessInformationService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 查询用户是否收藏过该信息
     */
    public boolean sfSc(Long userId, Long cId) {
        if (userId == null || cId == null) {
            return false;
        }

        LambdaQueryWrapper<BusinessCollect> lambdaQueryWrapper = new LambdaQueryWrapper<BusinessCollect>();
        lambdaQueryWrapper.eq(BusinessCollect::getUserId, userId);
        lambdaQueryWrapper.eq(BusinessCollect::getUserIdPassivity, cId);
        if (businessCollectService.getOne(lambdaQueryWrapper) != null) {
            return true;
        }

        return false;
    }
}
